import type { TestResultItem, SkyTestResult, GroundDirectionAccuracies } from "../../api/test/index.d";
import { updateSkyDirectionAccuracyTestResult, updateGroundDirectionAccuracyTestResult } from "../../api/test/index";
import type { ColumnItem } from "@xc-components/xc-table/types";
import { formatNumToTh } from "../../lib";
import type { TableColumnCtx } from "element-plus";
type Option = { label: string; prop: keyof TestResultItem };
interface TypeMap {
  type: number;
  chartType: string;
  x?: Option;
  y?: Option;
  config: ColumnItem<TestResultItem>[];
  seriesConfig?: Option[];
  onChange?: (value: any, row: any) => void;
}
interface SpanMethodProps {
  row: any;
  column: TableColumnCtx<any>;
  rowIndex: number;
  columnIndex: number;
}
export default function useConfig(content = {} as any) {
  const { taskId } = content;
  const typeMap: { [key: string]: { [key: string]: TypeMap } } = {
    无线电监测测向: {
      监测灵敏度: {
        type: 1,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "灵敏度(dBμV/m)", prop: "value" },
        config: [
          { label: "测试频率(MHz)", prop: "frequency" },
          { label: "频谱发现灵敏度(dBμV/m)", prop: "value" }
        ]
      },
      场强测量精度: {
        type: 2,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "精度(dB)", prop: "fieldAccuracy" },
        config: [
          { label: "测试频率(MHz)", prop: "frequency" },
          { label: "场强测量系统测试结果(dBμV/m)", prop: "fieldResult" },
          { label: "被测系统测量结果(dBμV/m)", prop: "underTestReuslt" },
          { label: "场强测量精度(dB)", prop: "fieldAccuracy" }
        ]
      },
      频率测量精度: {
        type: 3,
        chartType: "bar",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "精度", prop: "absoluteAccuracy" },
        seriesConfig: [
          { label: "绝对测量精度", prop: "absoluteAccuracy" },
          { label: "相对测量精度", prop: "relativeAccuracy" }
        ],
        config: [
          { label: "发射系统频率(MHz)", prop: "frequency" },
          { label: "被测系统读出频率(MHz)", prop: "underTestFrequency" },
          { label: "绝对测量精度(Hz)", prop: "absoluteAccuracy" },
          { label: "相对测量精度(10^-6)", prop: "relativeAccuracy" }
        ]
      },
      识别信号能力: {
        type: 4,
        chartType: "",
        config: []
      },
      测向灵敏度: {
        type: 5,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "场强读数(dBμV/m)", prop: "field" },
        config: [
          { label: "测试频率(MHz)", prop: "frequency" },
          { label: "大信号时的稳定示向度θ(°)", prop: "angle" },
          { label: "示向度偏离θ为6时场强测量系统读数(dBμV/m)", prop: "field" }
        ]
      },
      测向精度: {
        type: 6,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "均方差(°)", prop: "meanSquareError" },
        config: [
          { label: "频率(MHz)", prop: "frequency" },
          { label: "参考角度(°)", prop: "refAngle" },
          { label: "信号功率(dBm)", prop: "signalLevel" },
          { label: "示向度1(°)", prop: "angle001" },
          { label: "示向度2(°)", prop: "angle002" },
          { label: "示向度3(°)", prop: "angle003" },
          { label: "均值(°)", prop: "average" },
          { label: "均方差(°)", prop: "meanSquareError" }
        ]
      },
      带内抗扰度: {
        type: 7,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "带内抗扰度(dB)", prop: "inBandResult" },
        config: [
          { label: "频率(MHz)", prop: "frequency" },
          { label: "发射系统1输出功率(dBm)", prop: "output1" },
          { label: "发射系统2输出功率(dBm)", prop: "output2" },
          { label: "带内抗扰度(dB)", prop: "inBandResult" }
        ]
      },
      抑制度: {
        type: 8,
        chartType: "bar",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "互调抑制度(dB)", prop: "result" },
        seriesConfig: [{ label: "互调抑制度", prop: "result" }],
        config: [
          { label: "频率(MHz)", prop: "frequency" },
          { label: "输出功率P1(dBm)", prop: "p1" },
          { label: "输出功率P2(dBm)", prop: "p2" },
          { label: "互调抑制度(dB)", prop: "result" }
        ]
      },
      瞬时信号的监测和测向能力: {
        type: 9,
        chartType: "bar",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "时间(ms)", prop: "monitorTime" },
        seriesConfig: [
          { label: "监测最小驻留时间", prop: "monitorTime" },
          { label: "测向最小驻留时间", prop: "directionTime" }
        ],
        config: [
          { label: "发射系统频率(MHz)", prop: "frequency" },
          { label: "监测最小驻留时间(ms)", prop: "monitorTime" },
          { label: "测向最小驻留时间(ms)", prop: "directionTime" }
        ]
      }
    },
    固定站检测: {
      天波测向精度: {
        type: 16,
        chartType: "",
        config: [
          { label: "测试频率(kHz)", prop: "frequency", minWidth: "100" },
          {
            label: "监测时间",
            prop: "moniTime",
            type: "editable",
            editType: "datePicker",
            format: "YYYY-MM-DD HH:mm:ss",
            valueFormat: "YYYY-MM-DD HH:mm:ss",
            dateType: "datetime",
            minWidth: 150
          },
          { label: "发射类别", prop: "signalType", type: "editable", editType: "input" },
          { label: "台址", prop: "baseAdress", type: "editable", editType: "input" },
          { label: "纬度", prop: "latitude", type: "editable", editType: "input" },
          { label: "经度", prop: "longitude", type: "editable", editType: "input" },
          { label: "理论示向度θ", prop: "realAngle", type: "editable", editType: "input" },
          { label: "测试示向度θ", prop: "testAverage", type: "editable", editType: "input" },
          { label: "偏差Δθ", prop: "deviation", type: "editable", editType: "input" }
        ],
        onChange: (_: string, row: SkyTestResult) => {
          updateSkyDirectionAccuracyTestResult({ testResult: { ...row, moniTimeDatePicker: undefined } }, { taskId });
        }
      },
      地波测向精度: {
        type: 17,
        chartType: "",
        config: [
          { label: "频率(kHz)", prop: "frequency" },
          { label: "示向度θ", prop: "testAverage", type: "editable", editType: "input" },
          { label: "偏差Δθ", prop: "deviation", type: "editable", editType: "input" }
        ],
        onChange: (_: string, row: GroundDirectionAccuracies) => {
          updateGroundDirectionAccuracyTestResult({ testResult: row }, { taskId });
        }
      },
      监测灵敏度: {
        type: 10,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "监测灵敏度E(dBμV/m)", prop: "field" },
        config: [
          { label: "测试频率(MHz)", prop: "frequency", minWidth: "110" },
          { label: "E0(dBuV/m)", prop: "field0" },
          { label: "P1(dBm)", prop: "power1" },
          { label: "P2(dBm)", prop: "power2" },
          { label: "监测灵敏度E(dBμV/m)", prop: "field" }
        ]
      },
      测向灵敏度: {
        type: 11,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "监测灵敏度E(dBμV/m)", prop: "field" },
        config: [
          { label: "测试频率(MHz)", prop: "frequency", minWidth: "110" },
          { label: "示向度θ(°)", prop: "angle" },
          { label: "E0(dBμV/m)", prop: "field0" },
          { label: "P1(dBm)", prop: "power1" },
          { label: "P2(dBm)", prop: "power2" },
          { label: "监测灵敏度E(dBμV/m)", prop: "field" }
        ]
      },
      频率准确度: {
        type: 12,
        chartType: "bar",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "精度", prop: "absoluteAccuracy" },
        seriesConfig: [
          { label: "绝对测量精度", prop: "absoluteAccuracy" },
          { label: "相对测量精度", prop: "relativeAccuracy" }
        ],
        config: [
          { label: "发射系统频率(MHz)", prop: "frequency", minWidth: "130" },
          { label: "被测系统读出频率(MHz)", prop: "underTestFrequency" },
          { label: "绝对测量精度(Hz)", prop: "absoluteAccuracy" },
          { label: "相对测量精度(ppm)", prop: "relativeAccuracy" }
        ]
      },
      监测最小信号时长: {
        type: 13,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "监测最小信号时长(ms)", prop: "monitorTime" },
        config: [
          { label: "测试频率(MHz)", prop: "frequency" },
          { label: "监测最小信号时长(ms)", prop: "monitorTime" }
        ]
      },
      测向最小信号时长: {
        type: 14,
        chartType: "line",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "测向最小信号时长(ms)", prop: "directionTime" },
        config: [
          { label: "测试频率(MHz)", prop: "frequency" },
          { label: "测向最小信号时长(ms)", prop: "directionTime" }
        ]
      },
      抑制度: {
        type: 15,
        chartType: "bar",
        x: { label: "频率(MHz)", prop: "frequency" },
        y: { label: "互调抑制度(dB)", prop: "result" },
        seriesConfig: [{ label: "互调抑制度", prop: "result" }],
        config: [
          { label: "频率(MHz)", prop: "frequency", minWidth: "100" },
          { label: "输出功率P1(dBm)", prop: "p1" },
          { label: "输出功率P2(dBm)", prop: "p2" },
          { label: "互调抑制度(dB)", prop: "result" }
        ]
      }
    }
  };
  const getLineChartJson = (data: TestResultItem[] = [], row: TypeMap) => {
    return {
      grid: {
        top: 50,
        left: 60,
        right: 20,
        bottom: 40
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          lineStyle: {
            color: "#3A6EF6",
            width: 2
          }
        },
        // triggerOn: "click",
        className: "test-project-tooltip-box",
        textStyle: {
          color: "#1d2129",
          fontSize: 12
        },
        padding: 8,
        formatter: (vals: any) => {
          let html = `<div class="tit">${vals[0].axisValue}</div><div class="list">`;
          vals.forEach((it: any) => {
            const { value, seriesName } = it;
            html += `<div class="name-val">
              <span class="name">${seriesName}</span>
              <span class="val">${formatNumToTh(value)}</span>
            </div>`;
          });
          html += `</div>`;
          return html;
        }
      },
      xAxis: {
        type: "category",
        name: row.x?.label,
        nameTextStyle: {
          padding: [-20, 0, 0, -60],
          color: "#666",
          verticalAlign: "top"
        },
        boundaryGap: false,
        axisLine: {
          onZero: false,
          lineStyle: {
            color: "#ddd"
          }
        },
        axisLabel: {
          color: "#999"
          // interval: 4
        },
        data: data.map((it) => it[row.x?.prop as keyof TestResultItem])
      },
      yAxis: {
        type: "value",
        name: row.y?.label,
        nameTextStyle: {
          padding: [0, 0, 5, -20],
          color: "#666",
          align: "left"
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed",
            color: "#ddd"
          }
        },
        axisLabel: {
          color: "#999"
        }
      },
      series: [
        {
          type: "line",
          data: data.map((it) => it[row.y?.prop as keyof TestResultItem]),
          symbolSize: 0,
          name: row.y?.label,
          lineStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: "#13DAF1" },
                { offset: 1, color: "#3A6EF6" }
              ],
              global: false
            }
          },
          itemStyle: {
            color: "#3A6EF6",
            borderWidth: 2,
            borderColor: "#3A6EF6",
            opacity: 0
          },
          emphasis: {
            itemStyle: {
              opacity: 1
            }
          }
        }
      ]
    };
  };
  const getBarChartJson = (data: TestResultItem[] = [], row: TypeMap) => {
    return {
      color: ["#3A6EF6", "#13DAF1"],
      grid: {
        top: 50,
        left: 100,
        right: 20,
        bottom: 40
      },
      legend: {
        top: 10,
        itemGap: 20
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow"
        },
        className: "test-project-tooltip-box",
        textStyle: {
          color: "#1d2129",
          fontSize: 12
        },
        padding: 8,
        formatter: (vals: any[]) => {
          let html = `<div class="tit">${vals[0].axisValue}</div><div class="list">`;
          vals.forEach((it: any) => {
            const { value, seriesName, color } = it;
            html += `<div class="name-val">
              <span class="name"><i style="background: ${color}"></i>${seriesName}</span>
              <span class="val">${formatNumToTh(value)}</span>
            </div>`;
          });
          html += `</div>`;
          return html;
        }
      },
      xAxis: {
        type: "category",
        name: row.x?.label,
        nameTextStyle: {
          padding: [-20, 0, 0, -60],
          color: "#666",
          verticalAlign: "top"
        },
        boundaryGap: true,
        axisLine: {
          onZero: false,
          lineStyle: {
            color: "#ddd"
          }
        },
        axisLabel: {
          color: "#999"
        },
        data: data.map((it) => it[row.x?.prop as keyof TestResultItem])
      },
      yAxis: {
        type: "value",
        name: row.y?.label,
        nameTextStyle: {
          padding: [0, 0, 5, -20],
          color: "#666",
          align: "left"
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed",
            color: "#ddd"
          }
        },
        axisLabel: {
          color: "#999"
        }
      },
      series: row.seriesConfig?.map((it) => {
        return {
          name: it.label,
          type: "bar",
          barGap: 0,
          emphasis: {
            focus: "series"
          },
          barMinHeight: 10,
          barWidth: 30,
          data: data.map((x) => x[it.prop as keyof TestResultItem])
        };
      })
    };
  };
  function formatConfig(row: TypeMap, data: TestResultItem[]) {
    // 识别信号能力，额外处理
    if (row.type === 4) {
      let frequencyArr = data.map((it) => it.frequency);
      frequencyArr = frequencyArr.filter((it, i) => frequencyArr.indexOf(it) === i); // ["30","1450","5000"]
      const titleList: ColumnItem[] = frequencyArr.map((it) => {
        return { label: it + "MHz", prop: String(it) };
      });
      const fixedConfig: ColumnItem[] = [
        { label: "序号", prop: "index", width: "50", fixed: "left" },
        { label: "", prop: "type", width: "80" },
        { label: "", prop: "name", width: "100" }
      ];
      let types = data.map((it) => it.modlulitionType);
      types = types.filter((it, i) => types.indexOf(it) === i); // ["FM","AM","BPSK"]
      const tableData: any[] = [];
      types.forEach((it, i) => {
        const rows = data.filter((x) => x.modlulitionType === it);
        const obj1: { [key: string]: boolean } = {};
        const obj2: { [key: string]: number } = {};
        rows.forEach((x) => {
          obj1[String(x.frequency)] = x.isIdentify || false;
          obj2[String(x.frequency)] = x.identifyTime || 0;
        });
        tableData.push({ index: i + 1, type: it, name: "是否正确识别", ...obj1 }, { index: i + 1, type: it, name: "识别时长(s)", ...obj2 });
      });
      /**
       * @description: 合并行或列的计算方法
       * @param {SpanMethodProps} param1
       * @return {*}
       */
      const spanMethod = ({ rowIndex, columnIndex }: SpanMethodProps) => {
        if (columnIndex < 2) {
          if (rowIndex % 2 === 0) {
            return { rowspan: 2, colspan: 1 };
          } else {
            return { rowspan: 0, colspan: 0 };
          }
        }
      };
      return { config: data.length ? [...fixedConfig, ...titleList] : [], tableData, spanMethod, indexColumn: false };
    } else {
      const config = row.config?.map((it) => {
        row.onChange && (it.onChange = row.onChange);
        return it;
      });
      return { config, indexColumn: true };
    }
  }
  function getJson(name = "监测灵敏度", data: TestResultItem[] = [], type = "无线电监测测向") {

    if (name.includes("_")) {
      name = "测向精度";
    }

    const typeRow = typeMap[type] || {};
    const key = Object.keys(typeRow).find((it) => name.includes(it)) as keyof typeof typeRow;
    const row = typeRow[key] || {};

    // if (!row) {
    //   typeRow = typeMap["无线电监测测向"] || {};
    //   key = Object.keys(typeRow).find((it) => name.includes(it)) as keyof typeof typeRow;
    //   row = typeRow[key] || {};
    // }
    let json = {};
    if (row?.chartType === "line") {
      json = getLineChartJson(data, row);
    } else if (row?.chartType === "bar") {
      json = getBarChartJson(data, row);
    }
    const { config, tableData, spanMethod, indexColumn } = formatConfig(row, data);
    return { json, config, type: row.type, data: tableData, spanMethod, indexColumn };
  }
  return { getJson };
}
